import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:qilo/core/constants/app_icons.dart';
import '../../../core/models/hot_item.dart';
import '../../../core/providers/hot_item_provider.dart';
import '../pages/community_detail_page.dart';

/// Community page main content
class CommunityBody extends StatefulWidget {
  const CommunityBody({super.key});

  @override
  State<CommunityBody> createState() => _CommunityBodyState();
}

class _CommunityBodyState extends State<CommunityBody>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  late TabController _tabController;
  late AnimationController _indicatorAnimationController;
  late AnimationController _imageAnimationController;
  late Animation<double> _indicatorAnimation;
  late Animation<double> _imageAnimation;
  int _currentTabIndex = 0;

  final List<Map<String, String>> _monthTabs = [
    {'label': 'October', 'image': 'assets/images/october.png'},
    {'label': 'September', 'image': 'assets/images/september.png'},
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _monthTabs.length, vsync: this);

    // Initialize animation controllers
    _indicatorAnimationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _imageAnimationController = AnimationController(
      duration: const Duration(milliseconds: 400),
      vsync: this,
    );

    // Initialize animations
    _indicatorAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _indicatorAnimationController,
        curve: Curves.easeInOut,
      ),
    );

    _imageAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _imageAnimationController,
        curve: Curves.easeInOut,
      ),
    );

    // Start initial animations
    _indicatorAnimationController.forward();
    _imageAnimationController.forward();

    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        _handleTabChange(_tabController.index);
      }
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _indicatorAnimationController.dispose();
    _imageAnimationController.dispose();
    super.dispose();
  }

  /// Handle tab change with animations
  void _handleTabChange(int newIndex) async {
    if (newIndex != _currentTabIndex) {
      // Fade out current image
      await _imageAnimationController.reverse();

      // Update index
      setState(() {
        _currentTabIndex = newIndex;
      });

      // Fade in new image
      _imageAnimationController.forward();

      // Animate indicator
      _indicatorAnimationController.reset();
      _indicatorAnimationController.forward();
    }
  }

  /// Handle release button tap
  void _handleReleaseTap() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Release feature coming soon'),
        duration: Duration(seconds: 1),
      ),
    );
  }

  /// Handle post item tap
  void _handlePostTap(HotItem item) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => CommunityDetailPage(item: item)),
    );

    // 如果返回值为 true，表示需要刷新列表
    if (result == true && mounted) {
      // 刷新 HotItemProvider 数据
      final hotItemProvider = context.read<HotItemProvider>();
      hotItemProvider.refresh();
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // Required for AutomaticKeepAliveClientMixin
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/community-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SingleChildScrollView(
          child: SafeArea(
            bottom: false,
            child: Column(
              children: [
                // Top header
                _buildTopHeader(),

                // Month tabs and image section
                _buildMonthSection(),

                // Help section
                _buildHelpSection(),

                // Community posts grid
                _buildCommunityGrid(),

                // Bottom spacing
                SizedBox(height: 140.h),
              ],
            ),
          ),
        ),
        floatingActionButton: _buildReleaseButton(),
      ),
    );
  }

  /// Build top header
  Widget _buildTopHeader() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20.h),
      height: 99.w, // Set fixed height to accommodate the image
      child: Stack(
        children: [
          // Left side text
          Positioned(
            left: 0,
            top: 0,
            bottom: 0,
            right: 115.w, // Leave space for the image (99.w + 16.w margin)
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(
                'Musical Instruments Community',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontFamily: 'Porter Sans Block',
                  fontWeight: FontWeight.w400,
                  color: Colors.white,
                  shadows: [
                    Shadow(
                      offset: const Offset(1, 1),
                      blurRadius: 3,
                      color: Colors.black.withValues(alpha: 0.5),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Positioned(
            right: 0,
            top: 0,
            child: Container(
              width: 99.w,
              height: 99.w,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/community-top.png'),
                  fit: BoxFit.contain,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Build month section with tabs and images
  Widget _buildMonthSection() {
    return Container(
      height: 313.h,
      margin: EdgeInsets.only(left: 0, right: 16.w, top: 10.h, bottom: 10.h),
      child: Stack(
        children: [
          // Main image taking most of the space
          Positioned(
            left: 76.w, // Leave space for vertical text
            right: 0,
            top: 0,
            bottom: 0,
            child: _buildMonthImage(),
          ),

          // Vertical text tabs on the left
          Positioned(
            left: 16.w,
            top: 0,
            bottom: 0,
            child: _buildVerticalTabs(),
          ),
        ],
      ),
    );
  }

  /// Build vertical tabs
  Widget _buildVerticalTabs() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children:
          _monthTabs.asMap().entries.map((entry) {
            int index = entry.key;
            String label = entry.value['label']!;
            bool isSelected = _currentTabIndex == index;

            return GestureDetector(
              onTap: () {
                _handleTabChange(index);
                _tabController.animateTo(index);
              },
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.h),
                child: Row(
                  children: [
                    // Vertical text with animation
                    RotatedBox(
                      quarterTurns: 3, // Rotate 270 degrees (3 * 90)
                      child: AnimatedDefaultTextStyle(
                        duration: const Duration(milliseconds: 300),
                        curve: Curves.easeInOut,
                        style: TextStyle(
                          fontSize: isSelected ? 18.sp : 16.sp,
                          fontWeight:
                              isSelected ? FontWeight.bold : FontWeight.w500,
                          color:
                              isSelected
                                  ? Colors.white
                                  : Colors.white.withValues(alpha: 0.7),
                          letterSpacing: 2.0,
                          shadows: [
                            Shadow(
                              offset: const Offset(1, 1),
                              blurRadius: 3,
                              color: Colors.black.withValues(alpha: 0.5),
                            ),
                          ],
                        ),
                        child: Text(label),
                      ),
                    ),
                    SizedBox(width: 8.w),
                    // White indicator bar with animation
                    AnimatedBuilder(
                      animation: _indicatorAnimation,
                      builder: (context, child) {
                        return AnimatedContainer(
                          duration: const Duration(milliseconds: 300),
                          curve: Curves.easeInOut,
                          width: isSelected ? 3.w : 0,
                          height:
                              isSelected ? 40.h * _indicatorAnimation.value : 0,
                          decoration: BoxDecoration(
                            color: Colors.white.withValues(
                              alpha: isSelected ? _indicatorAnimation.value : 0,
                            ),
                            borderRadius: BorderRadius.circular(1.5.w),
                          ),
                        );
                      },
                    ),
                  ],
                ),
              ),
            );
          }).toList(),
    );
  }

  /// Build month image with fade animation
  Widget _buildMonthImage() {
    return GestureDetector(
      onVerticalDragEnd: (details) {
        if (details.primaryVelocity! > 0) {
          // Swipe down - previous tab
          if (_currentTabIndex > 0) {
            _tabController.animateTo(_currentTabIndex - 1);
          }
        } else if (details.primaryVelocity! < 0) {
          // Swipe up - next tab
          if (_currentTabIndex < _monthTabs.length - 1) {
            _tabController.animateTo(_currentTabIndex + 1);
          }
        }
      },
      child: AspectRatio(
        aspectRatio: 305 / 313,
        child: AnimatedBuilder(
          animation: _imageAnimation,
          builder: (context, child) {
            return FadeTransition(
              opacity: _imageAnimation,
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12.r),
                  image: DecorationImage(
                    image: AssetImage(_monthTabs[_currentTabIndex]['image']!),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  /// Build help section
  Widget _buildHelpSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20.h),
      child: AspectRatio(
        aspectRatio: 358 / 188,
        child: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/help.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
  }

  /// Build community posts grid
  Widget _buildCommunityGrid() {
    return Consumer<HotItemProvider>(
      builder: (context, hotItemProvider, child) {
        final items = hotItemProvider.hotItems;

        if (hotItemProvider.isLoading) {
          return Container(
            height: 200.h,
            margin: EdgeInsets.symmetric(horizontal: 16.w),
            child: const Center(child: CircularProgressIndicator()),
          );
        }

        if (items.isEmpty) {
          return Container(
            height: 200.h,
            margin: EdgeInsets.symmetric(horizontal: 16.w),
            child: Center(
              child: Text(
                'No community posts available',
                style: TextStyle(color: Colors.white, fontSize: 16.sp),
              ),
            ),
          );
        }

        return Container(
          margin: EdgeInsets.symmetric(horizontal: 16.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'COMMUNITY',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontFamily: 'Porter Sans Block',
                  color: Colors.white,
                  shadows: [
                    Shadow(
                      offset: const Offset(1, 1),
                      blurRadius: 3,
                      color: Colors.black.withValues(alpha: 0.5),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 16.h),
              GridView.builder(
                padding: EdgeInsets.zero,
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 172 / 193, // Keep original aspect ratio
                  crossAxisSpacing: 0.w,
                  mainAxisSpacing: 0.h,
                ),
                itemCount: items.length,
                itemBuilder: (context, index) {
                  return _buildCommunityItem(items[index]);
                },
              ),
            ],
          ),
        );
      },
    );
  }

  /// Build single community item
  Widget _buildCommunityItem(HotItem item) {
    return GestureDetector(
      onTap: () => _handlePostTap(item),
      child: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/card-bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Padding(
          padding: EdgeInsets.only(
            left: 20.w,
            right: 20.w,
            top: 20.h,
            bottom: 20.h,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Content image section
              Expanded(
                child: Stack(
                  children: [
                    // Content image
                    Container(
                      width: double.infinity,
                      height: double.infinity,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(8.r),
                        child: _buildItemImage(item),
                      ),
                    ),

                    // Video play icon for video type
                    if (item.isVideo)
                      Center(
                        child: Icon(
                          MyIcons.iconPlayFill,
                          color: Colors.white,
                          size: 22.sp,
                        ),
                      ),
                  ],
                ),
              ),

              SizedBox(height: 8.h),

              // Post information below image
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    item.title,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w600,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 2.h),
                  Text(
                    item.description,
                    style: TextStyle(
                      color: Colors.white.withValues(alpha: 0.8),
                      fontSize: 10.sp,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// Build item image
  Widget _buildItemImage(HotItem item) {
    final imageUrl = item.displayImageUrl;

    // Check if it's a local assets image
    if (imageUrl.startsWith('assets/')) {
      return Image.asset(
        imageUrl,
        fit: BoxFit.cover,
        width: double.infinity,
        height: double.infinity,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            color: Colors.grey[300],
            child: Icon(
              Icons.image_not_supported,
              color: Colors.grey[600],
              size: 40.sp,
            ),
          );
        },
      );
    }

    // Check if it's a local file path
    if (imageUrl.startsWith('/') || imageUrl.startsWith('file://')) {
      return Image.file(
        File(imageUrl.replaceFirst('file://', '')),
        fit: BoxFit.cover,
        width: double.infinity,
        height: double.infinity,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            color: Colors.grey[300],
            child: Icon(
              Icons.image_not_supported,
              color: Colors.grey[600],
              size: 40.sp,
            ),
          );
        },
      );
    }

    // Network image
    return Image.network(
      imageUrl,
      fit: BoxFit.fill,
      width: double.infinity,
      height: double.infinity,
      loadingBuilder: (context, child, loadingProgress) {
        if (loadingProgress == null) return child;
        return Container(
          color: Colors.grey[200],
          child: Center(
            child: CircularProgressIndicator(
              value:
                  loadingProgress.expectedTotalBytes != null
                      ? loadingProgress.cumulativeBytesLoaded /
                          loadingProgress.expectedTotalBytes!
                      : null,
            ),
          ),
        );
      },
      errorBuilder: (context, error, stackTrace) {
        return Container(
          color: Colors.grey[300],
          child: Icon(
            Icons.image_not_supported,
            color: Colors.grey[600],
            size: 40.sp,
          ),
        );
      },
    );
  }

  /// Build release floating action button
  Widget _buildReleaseButton() {
    return FloatingActionButton(
      onPressed: _handleReleaseTap,
      backgroundColor: Colors.orange,
      child: Icon(Icons.add, color: Colors.white, size: 24.sp),
    );
  }
}
